﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Cashier
{
    public partial class customer_form : Form
    {
        //public Dictionary<string, string> dictVipCodes;
        public AutoCompleteStringCollection sourceVipCode = new AutoCompleteStringCollection();
        public AutoCompleteStringCollection sourceVipName = new AutoCompleteStringCollection();
        public Thread threadUpDBFromServer;
        public customer_form()
        {
            InitializeComponent();
            this.FormClosing+=customer_form_FormClosing;
        }
        private DatabaseServices DBServices = new DatabaseServices();
        private void customer_form_Load(object sender, EventArgs e)
        {
            cb_searchby.SelectedIndex = 0;
        }

        private void btt_customer_new_Click(object sender, EventArgs e)
        {
            try
            {
                string _full_name = txt_customer_name.Text;
                string _address = txt_customer_address.Text;
                string _phone = txt_customer_phone.Text;
                int _gender = txt_customer_gender.SelectedIndex;
                string _join_date = txt_card_join_date.Text;
                txt_card_join_date.Text = "";
                txt_card_expire_date.Text = "";
                string _birthday = txt_customer_birthday.Text;
                string _card_id = txt_card_id.Text;
                int _vip = (int)cb_card_type.SelectedIndex;
                if (_card_id == "")
                {
                    MessageBox.Show("Missing Card ID!");
                    return;
                }
                Customer customer = new Customer();
                customer.full_name = _full_name;
                customer.address = _address;
                customer.phone = _phone;
                customer.vip = _vip;
                //customer.vi

                if (_gender == 1)
                {
                    customer.gender = true;
                }
                else
                {
                    customer.gender = false;
                }

                customer.join_date = DateTime.Now;
                customer.expire_date = customer.join_date.AddYears(1);
                if (_birthday != "") {
                    customer.birthday = Convert.ToDateTime(_birthday);
                }
                else {
                    customer.birthday = DateTime.Now;
                }
                customer.card_id = _card_id;
                if (customer.AddCustomerServer())
                {
                    LOG log = new LOG();
                    log.customer = customer;
                    if (log.AddCustomerLogServer() > 0)
                    {
                        MessageBox.Show("Thêm thành công!");
                    }
                }

                /*if(customer.AddCustomerLocal()){ 
                    LOG log = new LOG();
                    log.customer = customer;
                    if (log.AddCustomerLogLocal() > 0)
                    {
                        MessageBox.Show("Thêm thành công!");
                    }
                }*/
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship.  Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again."))
                {
                    MessageBox.Show("Card ID đã tồn tại !");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void customer_form_FormClosed(object sender, FormClosedEventArgs e)
        {
           
        }

        private void customer_form_FormClosing(object sender, FormClosingEventArgs e)
        {
            //login.ActiveForm.Show();
            if (threadUpDBFromServer != null && threadUpDBFromServer.ThreadState == ThreadState.Running)
                threadUpDBFromServer.Abort();
            FormManager.popForm();
        }

        private void DGV_customer_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        //    int i = int.Parse(DGV_customer.CurrentCell.RowIndex.ToString());
        //    string name = DGV_customer[1, i].Value.ToString();
        //    string phone = DGV_customer[2, i].Value.ToString();
        //    string address = DGV_customer[3, i].Value.ToString();
        //    string join_date = DGV_customer[4, i].Value.ToString();
        //    string point = DGV_customer[5, i].Value.ToString();
        //    string birthday = DGV_customer[6, i].Value.ToString();
        //    string gender = DGV_customer[7, i].Value.ToString();
        //    string is_vip = DGV_customer[8, i].Value.ToString();

        //    txt_customer_name.Text = name;
        //    txt_customer_phone.Text = phone;
        //    txt_customer_address.Text = address;
        //    txt_card_join_date.Text = join_date;
        //    txt_card_point.Text = point;
        //    txt_customer_birthday.Text = birthday;
        //    if (bool.Parse(gender))
        //    {
        //        txt_customer_gender.SelectedIndex = 0;
        //    }
        //    else
        //    {
        //        txt_customer_gender.SelectedIndex = 1;
        //    }
        //    if (bool.Parse(is_vip))
        //    {
        //        cb_card_type.SelectedIndex = 1;
        //    }
        //    else
        //    {
        //        cb_card_type.SelectedIndex = 0;
        //    }
        //    //txt_customer_gender.Text = gender;
        }

        protected virtual void txt_condition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                updateCustomerDGV();
            }
            
        }
        void updateCustomerDGV()
        {
            List<Customer> listcustomer = new List<Customer>();
            int x = cb_searchby.SelectedIndex;
            if (cb_searchby.SelectedIndex == 0)
            {
                listcustomer = DBServices.GetCustomerListByConditionServer("card_id LIKE '" + txt_condition.Text + "%'");
            }
            else if (cb_searchby.SelectedIndex == 1)
            {
                listcustomer = DBServices.GetCustomerListByConditionServer("full_name LIKE '%" + txt_condition.Text + "%'");
            }
            if (listcustomer.Count > 0)
            {
                DGV_customer.Rows.Clear();
                DGV_customer.Rows.Add(listcustomer.Count);
                DGV_customer.Refresh();
                int i = 0;
                foreach (Customer customer in listcustomer)
                {
                    DGV_customer[0, i].Value = customer.card_id;
                    DGV_customer[1, i].Value = customer.full_name;
                    DGV_customer[2, i].Value = customer.phone;
                    DGV_customer[3, i].Value = customer.address;
                    DGV_customer[4, i].Value = customer.join_date.Date.ToString();
                    DGV_customer[5, i].Value = customer.point;
                    DGV_customer[6, i].Value = customer.birthday.Date.ToString();
                    DGV_customer[7, i].Value = customer.gender;
                    DGV_customer[8, i].Value = customer.vip;
                    i++;
                }
            }
        }

        private void DGV_customer_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(DGV_customer.CurrentCell.RowIndex.ToString());
                if (DGV_customer.RowCount == 0) return;
                if (DGV_customer.ColumnCount == 0) return;
                //setup default cell value to avoid bug info table dont show when select row has cell.value = null
                for (int k = 0; k < 7; k++) //k must < 7 to ignore boolean column
                {
                    if (DGV_customer[k, i].Value == null)
                        DGV_customer[k, i].Value = ""; 
                }
                string card_id = DGV_customer[0, i].Value.ToString();
                string name = DGV_customer[1, i].Value.ToString();
                string phone = DGV_customer[2, i].Value.ToString();
                string address = DGV_customer[3, i].Value.ToString();
                string join_date = DGV_customer[4, i].Value.ToString();
                string point = DGV_customer[5, i].Value.ToString();
                string birthday = DGV_customer[6, i].Value.ToString();
                string gender = DGV_customer[7, i].Value.ToString();
                int vip = int.Parse(DGV_customer[8, i].Value.ToString());
                DateTime Expired_date = (DateTime.Parse(join_date)).AddYears(1);

                txt_card_id.Text = card_id;
                txt_customer_name.Text = name;
                txt_customer_phone.Text = phone;
                txt_customer_address.Text = address;
                txt_card_join_date.Text = join_date;
                txt_card_expire_date.Text = Expired_date.ToString();
                txt_card_point.Text = point;
                txt_customer_birthday.Text = birthday;
                cb_card_type.SelectedIndex = vip;
                if (bool.Parse(gender))
                {
                    txt_customer_gender.SelectedIndex = 0;
                }
                else
                {
                    txt_customer_gender.SelectedIndex = 1;
                }
                if (txt_card_id.Text != "")
                {
                    btt_customer_update.Enabled = true;
                }
            }
            catch(Exception ex){
               // MessageBox.Show(ex.ToString());
            }
        }

        private void btt_customer_update_Click(object sender, EventArgs e)
        {
            try
            {
                string full_name = txt_customer_name.Text;
                string address = txt_customer_address.Text;
                string phone = txt_customer_phone.Text;
                int gender = txt_customer_gender.SelectedIndex;
                string join_date = txt_card_join_date.Text;
                string birthday = txt_customer_birthday.Text;
                string card_id = txt_card_id.Text;
                int vip = cb_card_type.SelectedIndex;
                Customer customer = new Customer();
                customer.full_name = full_name;
                customer.address = address;
                customer.phone = phone;
                customer.vip = vip;
                if (gender == 1)
                {
                    customer.gender = true;
                }
                else
                {
                    customer.gender = false;
                }
                customer.join_date = DateTime.Parse(join_date);
                customer.birthday = DateTime.Parse(birthday);
                customer.card_id = card_id;
                if (customer.UpdateCustomerServerData())
                {
                    LOG log = new LOG();
                    log.customer = customer;
                    //if (log.UpdateCustomerServer())
                    {
                        MessageBox.Show("Update Successful");
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void txt_condition_TextChanged(object sender, EventArgs e)
        {

        }

        private void cb_searchby_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cb_searchby.SelectedItem.ToString() == "CardID")
                {
                    txt_condition.AutoCompleteCustomSource = sourceVipCode;
                }
                if (cb_searchby.SelectedItem.ToString() == "Name")
                {
                    txt_condition.AutoCompleteCustomSource = sourceVipName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btt_print_barcode_card_Click(object sender, EventArgs e)
        {

        }

        private void btt_new_card_Click(object sender, EventArgs e)
        {
            updateCustomerDGV();
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            this.Close();
            FormManager.pushForm(new customer_form());

        }

        private void btUpdateLocalDb_Click(object sender, EventArgs e)
        {
            if (threadUpDBFromServer != null && threadUpDBFromServer.ThreadState == ThreadState.Running)
            {
                MessageBox.Show("Local Database is updating");
                return;
            }
            try
            {
                threadUpDBFromServer = new Thread(refreshLocalDB);
                threadUpDBFromServer.Start();
            }
            catch (Exception ex)
            {
                threadUpDBFromServer.Abort();
                MessageBox.Show(ex.ToString());
            }
        }

        private void refreshLocalDB()
        {
            DatabaseServices.refreshAccessDb();
            MessageBox.Show("Update Database Local Completed !!");
            threadUpDBFromServer.Abort();
            
        }



        
    }
}
